package com.ling.service;

import com.ling.bean.Area;
import com.ling.bean.UserArea;
import com.ling.bean.UserAreaExample;
import com.ling.dao.UserAreaMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author lin
 */
@Service
public class UserAreaService {

    private final UserAreaMapper userAreaMapper;

    @Autowired
    public UserAreaService(UserAreaMapper userAreaMapper) {
        this.userAreaMapper = userAreaMapper;
    }

    //获取指定用户userId的关注领域
    public List<UserArea> getUserAreasByUserId(String userId) {
        return userAreaMapper.selectUserAreasByUserId(userId);
    }

    //删除指定用户关注记录
    public void deleteUserArea(String userId,String areaId) {
        UserAreaExample userAreaExample = new UserAreaExample();
        userAreaExample.createCriteria().andUseridEqualTo(userId).andAreaidEqualTo(areaId);
        userAreaMapper.deleteByExample(userAreaExample);
    }

    //获取指定用户未关注的领域
    public List<Area> getUserUnStarArea(String userId) {
        return userAreaMapper.selectUserUnstarAreasByUserId(userId);
    }

    //保存用户选择的领域
    public void saveUserArea(UserArea userArea) {
        //判断该记录是否已经存在
        if (isExistUserArea(userArea)) {
            return ;
        }
        userAreaMapper.insertSelective(userArea);
    }

    //查询是否存在指定记录
    private boolean isExistUserArea(UserArea userArea) {
        UserAreaExample userAreaExample = new UserAreaExample();
        userAreaExample.createCriteria().andUseridEqualTo(userArea.getUserid()).andAreaidEqualTo(userArea.getAreaid());
        return userAreaMapper.countByExample(userAreaExample)>0;
    }

    //根据userId和areaId查询
    public UserArea getUserArea(String userId, String areaId) {
        UserAreaExample userAreaExample = new UserAreaExample();
        userAreaExample.createCriteria().andUseridEqualTo(userId).andAreaidEqualTo(areaId);
        List<UserArea> userAreas = userAreaMapper.selectByExample(userAreaExample);
        if (userAreas.isEmpty()) {
            return null;
        }
        return userAreas.get(0);
    }

    //更新ability
    public void updateAbility(UserArea userArea) {
        userAreaMapper.updateByPrimaryKeySelective(userArea);
    }
}
